
import {
  NOTE_SWITCH,
  NOTE_LIST_RESET,
  NOTE_ADD,
  NOTE_REMOVE,
  NOTE_SYNC
} from '../actions/actionTypes';
let initialNoteState = {
  items: [],
  current: undefined
};

export default function (state = initialNoteState, action) {
    switch (action.type) {
      case NOTE_SWITCH:
        return Object.assign({}, state, {type: action.type, current: action.note});
      case NOTE_LIST_RESET:
        return Object.assign({}, state, {type: action.type, items: action.items});
      case NOTE_ADD:
        return Object.assign({}, state, {type: action.type, items: [action.note].concat(state.items)});
      case NOTE_REMOVE:
        return Object.assign({}, state, {
          type: action.type,
          items: state.items.filter((item)=> item._id != action.note._id)
        });
      case NOTE_SYNC:
        return Object.assign({}, state, {
          type: action.type,
          current: state.current._id == action.note._id ? Object.assign(state.current, action.note) : state.current,
          items: state.items.map((item)=> item._id == action.note._id ? Object.assign(item, action.note) : item).sort((a, b)=>b.dateUpdated - a.dateUpdated)
        });
    }
    return Object.assign({}, state, {type: action.type});
  }